#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Config.PackPath import LOGS_DIR, CONFIG_DIR
from logging.handlers import TimedRotatingFileHandler
import json
import logging
import time
import os

try:
    config_file_path = os.path.join(CONFIG_DIR, 'LocalMachineConfig.json')
    with open(config_file_path, 'r', encoding='utf-8') as r:
        config_dict = json.load(r)
    log_level = config_dict['LogLevel']
    log_file_record = config_dict['LogFileRecord']
except Exception as e:
    print('读取ScriptExcelConfig.json文件失败')
    raise e


class Logger:

    def __init__(self, logger_name=__name__):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        now_time = time.strftime("%Y-%m-%d_%H-%M-%S")
        self.log_file_name = '{0}.log'.format(now_time)
        if not os.path.exists(LOGS_DIR):
            os.makedirs(LOGS_DIR)
        self.log_file_path = os.path.join(LOGS_DIR, self.log_file_name)
        self.formatter = logging.Formatter(
            # '[%(asctime)s][%(levelname)s][%(module)s][%(funcName)s][%(lineno)d]: %(message)s')
            '[%(asctime)s][%(levelname)s]: %(message)s')
        self.console_output_level = log_level
        self.file_output_level = 'DEBUG'
        self.backup_count = 20

    def get_logger(self, if_log_file=log_file_record):
        """在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回"""
        if not self.logger.handlers:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(self.console_output_level)
            console_handler.setFormatter(self.formatter)
            self.logger.addHandler(console_handler)
            if if_log_file:
                file_handler = TimedRotatingFileHandler(filename=self.log_file_path, when='D', interval=1,
                                                        backupCount=self.backup_count, delay=True, encoding='utf-8')
                file_handler.setLevel(self.file_output_level)
                file_handler.setFormatter(self.formatter)
                self.logger.addHandler(file_handler)
        return self.logger


logger = Logger().get_logger()
